<template>
  <el-drawer @close="drawerClose" size="450px" v-model="drawerVisible" :title="`新增用户`">
    <el-scrollbar>
      <el-form ref="ruleFormRef" label-width="100px" :model="reformData" label-suffix=" :" :rules="rules">
        <el-form-item label="用户头像" prop="imageUrl">
          <ImageUpload ref="clearImg" @getImgurl="getImgurl"></ImageUpload>
        </el-form-item>
        <el-form-item label="用户姓名" prop="staffName">
          <el-input v-model="reformData.staffName" placeholder="请填写用户姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="reformData.gender" placeholder="请选择性别" clearable>
            <el-option v-for="item in genderType" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="身份" prop="class">
          <el-select v-model="reformData.class" placeholder="请选择用户身份" clearable>
            <el-option v-for="item in classType" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input v-model="reformData.age" placeholder="请输入年龄" clearable></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="reformData.idCard" placeholder="请填写身份证号" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="iphone">
          <el-input v-model="reformData.iphone" placeholder="请填写手机号" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="reformData.password" placeholder="请填写密码" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="mailbox">
          <el-input v-model="reformData.mailbox" placeholder="请填写邮箱" clearable></el-input>
        </el-form-item>
        <el-form-item label="居住地址" prop="address">
          <el-input v-model="reformData.address" placeholder="请填写居住地址" clearable></el-input>
        </el-form-item>
      </el-form>
    </el-scrollbar>

    <template #footer>
      <el-button @click="reset(ruleFormRef)">取消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
    </template>
  </el-drawer>
</template>

<script  setup>
import ImageUpload from "@/components/Upload/uImg.vue"
import { computed, reactive, ref, watchEffect, toRaw ,watch, onMounted, onUpdated,} from "vue";
// import { staffData } from "@/stores/staff.js"
import { ElLoading, ElMessage } from 'element-plus'
import {userManage} from "@/stores/user.js"

import {baseUrl} from "@/utils/util"
// import { ElMessage, FormInstance } from "element-plus";

let userManageOperate = userManage()
// let mStaff = {}
let props = defineProps({
  // controlDrawer:{
  //     type:Boolean,
  //     default:false
  // }
});


let ruleFormRef = ref()

let clearImg = ref()

let emit = defineEmits(["update:controlDrawer","uploadSuccess"]);

// let reformData = reactive({
//   staffName: "何其芳",
//   idCard: "450922200108021733",
//   gender: "1",
//   address: "广西玉林市陆川县沙坡镇沙坡村中间屋8号",
//   mailbox: "615851181@qq.com",
//   imageUrl: "",
//   iphone: "18776382314",
//   age:"17",
//   password:"123123",
//   class:"1"

// });


let reformData = reactive({
  staffName: "",
  idCard: "",
  gender: "",
  address: "",
  mailbox: "",
  imageUrl: "",
  iphone: "",
  age:"",
  password:"",
  class:""

});

let checkphone = (rule, value, callback) => {
  let reg = /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/
  if (!value) {
    return callback(new Error("请输入用户的手机号"))
  }

  if (!reg.test(value)) {
    callback(new Error('请输入正确的手机号'))
  }
  callback()
}

let checkMailbox = (rule, value, callback) => {
  let reg = /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/
  if (!value) {
    return callback(new Error("请输入邮箱地址"))
  }
  if (!reg.test(value)) {
    return callback(new Error("请输入正确的邮箱地址"))
  }
  callback()
}

let checkIdcard = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("请输入身份证"))
  }
  // console.log(value.length ==18)
  // let reg = /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  if (value.length !== 18) {
    return callback(new Error("请输入正确的身份号"))
  }

  callback()
}

let rules = reactive({
  staffName: [
    { required: true, message: '请输入用户的名字', trigger: 'blur' },
  ],
  password:[
  { required: true, message: '请输入你的密码', trigger: 'blur' },
  ],
  age:[
    { required: true, message: '请输入用户的年龄', trigger: 'blur' },
  ],
  idCard: [
    { required: true, message: '请输入用户的身份证', trigger: 'blur' },
    { validator: checkIdcard, trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请输选择性别', trigger: 'change' },
  ],
  class: [
    { required: true, message: '请输选择身份', trigger: 'change' },
  ],
  address: [
    { required: true, message: '请输入用户的地址', trigger: 'blur' },
  ],
  mailbox: [
    { required: true, message: '请输入用户的邮箱', trigger: 'blur' },
    { validator: checkMailbox, trigger: 'blur' }
  ],
  imageUrl: [
    { required: true, message: '请输入用户的头像', trigger: 'blur' },
  ],
  iphone: [
    { required: true, message: '请输入用户的手机号码', trigger: 'blur' },
    { validator: checkphone, trigger: 'blur' }
  ],

})

let genderType = reactive([
  {
    name: "男",
    value: "1",
  },
  {
    name: "女",
    value: "2",
  },
]);

let classType = reactive([
  {
    name: "管理员",
    value: 1,
  },
  {
    name: "商家",
    value: 2,
  },
]);

let drawerVisible = ref(false);

let acceptParams = (params) => {
  drawerVisible.value = params;

};

//从staff仓库中拿staffdata数据渲染在表格上
watch(()=>userManageOperate.userData,(e)=>{
  // console.log(baseUrl(),"stayaohfe")
  reformData.staffName = e.name?e.name:""
    reformData.idCard = e.idCard?e.idCard:""
    reformData.gender = e.gender?e.gender:""
    reformData.address = e.address?e.address:""
    reformData.mailbox = e.mailbox?e.mailbox:""
    reformData.imageUrl = e.imageUrl?e.imageUrl:""
    reformData.iphone = e.iphone?e.iphone:""
    reformData.age = e.age?e.age:"",
    reformData.class = e.class?e.class:""
    reformData.password = "123123"
},{deep:true})



// 上传数据
let submitForm = (formEl) => {
  // console.log(reformData)
  // return
  formEl.validate((valid) => {
    if (valid) {
      getYaoData()
      // console.log('submit!')
    } else {
      console.log('error submit!')
    }
  })
}

// let 接受数据
let getYaoData = async () => {
  let data = toRaw(reformData)
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {

    // console.log(data,"data")

    let res = await userManageOperate.registerUser(data)
    // console.log(res,"注册返回的数据")
    // let res = await mStaff.getStaffRegisterData(data)
    // console.log(res)
    if (res.code == 200) {
      reset(ruleFormRef.value)
      emit("uploadSuccess")
      ElMessage({
        showClose: true,
        message: res.mess,
        type: 'success',
      })
    } else {
      ElMessage({
        showClose: true,
        message: res.mess,
        type: 'error',
      })
    }
  } finally {
    setTimeout(()=>{
      loading.close()
    },1000)
  }

}

let drawerClose = ()=>{
  // console.log("关闭的回调")
  userManageOperate.$patch((state)=>{
    // console.log(state.userData,"这是user仓库里面的数据")
    state.userData = {}
  })
  Object.assign(reformData,{})
  ruleFormRef.value.resetFields()
}



// 挂载的时候传图片地址给ImageUpload

onUpdated(()=>{
  // console.log(reformData.imageUrl, "已挂载为什么就挂在了")
  userManageOperate.imgUrl = reformData.imageUrl
  
})

// 重置数据
let reset = (formEl) => {
  if (!formEl) return
  clearImg.value.clearImg()
  formEl.resetFields()
  drawerVisible.value = false
}

//获取上传的图片 地址
let getImgurl = (e) => {
  // console.log(e, "我是父亲")
  reformData.imageUrl = e
}

defineExpose({
  acceptParams,
});
</script>


<style lang="scss" scoped></style>